package com.yu.weixinsms.task;

import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.lang.Tuple;
import com.alibaba.fastjson.JSONObject;
import com.nlf.calendar.Lunar;
import com.yu.weixinsms.Model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.RawResponse;
import net.dongliu.requests.Requests;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class PushMessageTask {
    private static int count = 0;

    @Value("${weixin.province}")
    private String province;
    @Value("${weixin.city}")
    private String city;
    @Value("${weixin.Users}")
    private String users;
    @Value("${weixin.templateId}")
    private String templateId;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void weiXinMessage() {
        TemperatureDto temperature = null;
        try (InputStream input = PushMessageTask.class.getResourceAsStream("/data.json")) {
            String cityCode = IOUtils.toString(input, StandardCharsets.UTF_8);
            temperature = getTemperature(cityCode);//拿到天气信息
        } catch (Exception e) {
            log.error("读取json出错：{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        String shidu = temperature.getData().getShidu();
        String quality = temperature.getData().getQuality();//空气质量
        String high = temperature.getData().getForecast().get(0).getHigh();
        String low = temperature.getData().getForecast().get(0).getLow();
        String type = temperature.getData().getForecast().get(0).getType();
        String notice = temperature.getData().getForecast().get(0).getNotice();//注意点

        long birthdayCount = getBirthdayCount();//距离生日天数
        Pair commemorationDay = getCommemorationDay();//纪念日
        Pair yiAndJi = getYiAndJi();//获取今日宜忌
        String quotation = getQuotation();//每日语录

        MessagePushRequest request = new MessagePushRequest();
        request.setTouser(users);
        request.setTemplateId(templateId);
        MessagePushRequest.DataDTO dataDTO = new MessagePushRequest.DataDTO();

        MessagePushRequest.DataDTO.Keyword1DTO date = new MessagePushRequest.DataDTO.Keyword1DTO();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String datetime = simpleDateFormat.format(new Date());
        date.setValue(datetime);
        date.setColor("#F8C4D1");
        dataDTO.setDate(date);

        MessagePushRequest.DataDTO.Keyword2DTO cityDto = new MessagePushRequest.DataDTO.Keyword2DTO();
        cityDto.setValue(city);
        cityDto.setColor("#974E5F");
        dataDTO.setCity(cityDto);

        MessagePushRequest.DataDTO.Keyword3DTO qualityDto = new MessagePushRequest.DataDTO.Keyword3DTO();
        qualityDto.setValue(type+","+low+","+high+",空气质量："+quality+","+notice);
        qualityDto.setColor("#F8C4D1");
        dataDTO.setQuality(qualityDto);

        MessagePushRequest.DataDTO.Keyword4DTO birthdayCountDto = new MessagePushRequest.DataDTO.Keyword4DTO();
        birthdayCountDto.setValue(birthdayCount+"");
        birthdayCountDto.setColor("#974E5F");
        dataDTO.setBirthdayCount(birthdayCountDto);

        MessagePushRequest.DataDTO.Keyword5DTO dayCountDto = new MessagePushRequest.DataDTO.Keyword5DTO();
        dayCountDto.setValue(commemorationDay.getKey().toString());
        dayCountDto.setColor("#F8C4D1");
        dataDTO.setDayCount(dayCountDto);

        MessagePushRequest.DataDTO.Keyword6DTO minCountDto = new MessagePushRequest.DataDTO.Keyword6DTO();
        long key = (long)commemorationDay.getKey();
        long value =  (long)commemorationDay.getValue();
        long min = key - value;
        minCountDto.setValue(min+"");
        minCountDto.setColor("#974E5F");
        dataDTO.setMinCount(minCountDto);

        MessagePushRequest.DataDTO.Keyword7DTO yiDto = new MessagePushRequest.DataDTO.Keyword7DTO();
        yiDto.setValue(yiAndJi.getKey().toString());
        yiDto.setColor("#F8C4D1");
        dataDTO.setYi(yiDto);

        MessagePushRequest.DataDTO.Keyword8DTO jiDto = new MessagePushRequest.DataDTO.Keyword8DTO();
        jiDto.setValue(yiAndJi.getValue().toString());
        jiDto.setColor("#974E5F");
        dataDTO.setJi(jiDto);
        request.setData(dataDTO);

        String requestData = JSONObject.toJSONString(request);
        String token = getToken();
        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        RawResponse rawResponse = null;
        try {
            rawResponse = Requests.post(postUrl).timeout(10 * 1000, 60 * 1000).body(requestData).send();
        } catch (Exception e) {
          log.error(e.getMessage());
        }
        String respBody = new String(rawResponse.readToBytes(), StandardCharsets.UTF_8);
        log.info("发送成功：result:{}",respBody);
    }
    public static String getToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx0673ac6fbba27087&secret=bd4c4bec946c65cab69869d16c349913";
        RawResponse rawResponse = null;
        try {
            rawResponse = Requests.get(url).timeout(10 * 1000, 60 * 1000).send();
        } catch (Exception e) {
            log.error("获取token出错{}", e.getMessage());
        }
        String respBody = new String(rawResponse.readToBytes(), StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(respBody);
        String token = (String)jsonObject.get("access_token");
        return token;
    }

    public  String getQuotation() {
        try (InputStream input = PushMessageTask.class.getResourceAsStream("/quotation.txt")) {
            String cityCode = IOUtils.toString(input, StandardCharsets.UTF_8);
            String[] split = cityCode.split("\r");
            if (count==split.length){
                count = 0;
            }
            return split[count++];
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }




    public Pair getCommemorationDay() {
        ArrayList<Long> CommemorationDay = new ArrayList<>();
        CommemorationDay.add(1000l);
        CommemorationDay.add(1500l);
        CommemorationDay.add(2000l);
        CommemorationDay.add(2500l);
        CommemorationDay.add(3000l);
        long l = (new DateTime().getTime() - new DateTime("2020-07-09").getTime()) / (1000 * 60 * 60 * 24);
        for (Long integer : CommemorationDay) {
            if (integer > l) {
                return Pair.of(integer, l);
            }
        }
        return Pair.of(1, 2);
    }

    public long getBirthdayCount() {
        long days = 0;
        String birthdayYear = "2023-08-07 12:00:00,2024-07-26 12:00:00,2025-07-15 12:00:00,2026-08-03 12:00:00,2027-07-24 12:00:00";
        List<String> yearList = Arrays.asList(birthdayYear.split(","));
        for (String list : yearList) {
            long dateTime = new DateTime().getTime();//当前时间戳
            long birthTime = new DateTime(list).getTime();//生日时间戳
            if (dateTime < birthTime) {
                days = (birthTime - dateTime) / (1000 * 60 * 60 * 24);
                break;
            }
        }
        return days;
    }

    public TemperatureDto getTemperature(String cityCode) {
        String url = "http://t.weather.itboy.net/api/weather/city/";
        String CityCode ="";
        WeatherCode weatherCode = JSONObject.parseObject(cityCode, WeatherCode.class);
        List<ProvinceCode> provinceCodes = weatherCode.getProvinceCodes();

        for (ProvinceCode provinceCode : provinceCodes) {
            if (province.equals(provinceCode.getProvince())) {
                for(CityCode code:provinceCode.getCityCodeList()){
                    if (city.equals(code.getCityName())) {
                        CityCode = code.getCityCode();
                        break;
                    }
                }
            }
        }

        url = url + CityCode;
        RawResponse rawResponse = null;
        try {
            rawResponse = Requests.get(url).timeout(10 * 1000, 60 * 1000).send();
        } catch (Exception e) {
            log.error("调用外部天气接口出错{}", e.getMessage());
        }

        String respBody = new String(rawResponse.readToBytes(), StandardCharsets.UTF_8);
        TemperatureDto temperatureDto = JSONObject.parseObject(respBody, TemperatureDto.class);
        return temperatureDto;
    }

    public Pair getYiAndJi() {
        Lunar date = new Lunar();
        List<String> dayYi = date.getDayYi();
        List<String> dayJi = date.getDayJi();
        return Pair.of( dayYi.toString(),dayJi.toString());
    }

    public static void main(String[] args) {

    }

}
